<style lang="less" scoped>
.panel-empty{
  min-height: 300px;
  border-top: 1px solid #ddd;
  box-shadow: none;
  border-radius: 0;
  .icon-panel{
    margin-top: 60px;
    color: #ddd;
    h4{
      margin-bottom: 60px;
    }
  }
}
.delete_btn{
  cursor: pointer;
  color: #EA5C5C;
}
.more-width{
  padding-left: 30px;
  padding-right: 30px;
}
</style>

<template>
    <div class="row margin-reset carts-index">
        <div class="col-xs-12 top-row">
            <div class="pull-right">
                <a href="/products">
                    <i class="fa fa-angle-left"></i> 返回购物
                </a>
            </div>
            <h4>购物车</h4>
        </div>

        <div class="col-xs-12">
                  <div class="panel panel-empty" v-if="emptyCarts">
          <div class="icon-panel text-center">
            <i class="fa fa-puzzle-piece fa-4x"></i>
            <h4>购物车是空的</h4>
            <a href="/products" class="btn btn-primary btn-lg more-width">立即逛逛</a>
          </div>
        </div>

        <table class="table carts-table" v-if="!emptyCarts">
            <thead>
                <tr>
                    <td class="col-xs-1">&nbsp;</td>
                    <td>产品名称</td>
                    <td class="text-right">价格</td>
                    <td class="text-right">数量</td>
                    <td class="col-xs-3 text-right">小计</td>
                    <td>&nbsp;</td>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item, $index) in items">
                    <td>
                        <input type="checkbox" :value="item.id" v-model="item.checked" />
                    </td>
                    <td>
                        <img :src="item.product.main_img_url" :alt="item.product.title" style="width:60px;height:60px;">
                        <a :href="generateUrl(item.product.id)">{{ item.product.title }}</a>
                    </td>
                    <td class="text-right">
                        ¥ {{ item.product.msrp }}
                    </td>
                    <td class="pull-right">
                        <input-number :amount="item.amount" :items="items" :itemIndex="$index" :customFun="cartCustomFun($index)"></input-number>
                    </td>
                    <td class="text-right">
                        ￥ {{ item.subTotal }}
                    </td>
                    <td class="text-center">
                        <a class="delete_btn" @click="deleteItem($index)">删除</a>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" v-model="checkedAll"> 全选
                    </td>
                    <td>
                       <span @click="batchDelete">删除选中产品</span>
                    </td>
                    <td colspan="2"></td>
                    <td>
                        已选{{totalQuantity}}件商品,共计<span class="totalPrice">￥{{total}}</span>
                    </td>
                    <td>
                        <a class="btn btn-primary btn-lg more-width" href="/orders/new" @click="checkout">结算</a>
                    </td>
                </tr>
            </tbody>
        </table>
        </div>
    </div>
</template>

<script>

import InputNumber from './inputNumber.vue'
import Query from '../query.js'
import ErrorDialog from 'error_alert.coffee'

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
}

export default {
    components: {
        'input-number': InputNumber
    },

    data() {
        return {
            items: [],
            cartCustomFun: function (index) {
              let self = this
              return function(inputValue, callback) {
                let cart = this.items[index]
                Query.put("/carts/" + cart.id, {
                        amount: inputValue,
                        product_id: cart.product.id
                      }).then(function(resp) {
                        let flag = resp.flag
                        if(flag) {
                          let item = self.items[index]
                          let price = item.product.msrp
                          self.items[index].subTotal = price * inputValue
                          self.items[index].amount = inputValue
                        }else {
                          ErrorDialog.show(resp.message)
                        }
                        callback.call(this, flag)
                      })
              }
            }
        }
    },

    computed: {
        totalQuantity: {
          get: function() {
            let checkouted = this.items.filter(function(item){return item.checked})
            return checkouted.reduce((a, b) =>  a + b.amount, 0)
          }
        },

        fieldQuantity: {
          get: function() {
            return this.items.filter(function(item){return item.checked}).length
          }
        },
        checkedAll: {
          get: function() {
            console.log('checkedAll', this.fieldQuantity)
            return this.fieldQuantity == this.items.length
          },
          set: function(value) {
            this.items = this.items.map(function(item){item.checked=value;return item;});
          }
        },
        total: {
          get: function() {
            return this.totalPrice(this.items)
          }
        },
        emptyCarts: {
          get: function() {
            return this.items.length <= 0
          }
        }
    },

    mounted() {
        this.initData();
    },

    methods: {
        async initData() {
            let self = this
            await Query.get("/carts/get_data").then(function (data) {
                let merchants = Object.keys(data)
                if (merchants.length > 0) {
                    let merchant = merchants[0]
                    data = data[merchant].carts
                    for(let i=0;i< data.length;i++){
                      let item = data[i]
                      data[i].subTotal = item.product.msrp * item.amount
                      data[i].checked = true
                    }
                    self.items = data
                    self.totalQuantity = self.items.length
                }
            })
        },

        async deleteItem(index) {
          let id = this.items[index].id
          this.items.remove(index)
          await Query.delete('/carts/' + id).then(function(resp) {
            if(!resp.flag) {
              ErrorDialog.show(resp.message)
            }
          })
        },

        async batchDelete() {
          let deleted = this.items.filter(function(item){return item.checked})
          let self = this
          await Query.post('/carts/batch_destroy', {
            ids: deleted.map(function(item) { return item.id})
          }).then(function(resp) {
            if(resp.flag){
              self.items = self.items.filter(function(item){return !item.checked})
              self.items.map(function(item){ item.checked = true})
              self.totalQuantity = self.items.length
            }else {
              ErrorDialog.show(resp.message)
            }
          })

        },

        async checkout(e) {
          e.preventDefault()
          if(this.totalQuantity > 0){
            let deletedIds = this.items.filter(function(item){return !item.checked}).map(function(item){return item.id})
            if(deletedIds.length>0) {
              await Query.post('/carts/batch_destroy', {
                ids: deletedIds
              }).then(function(resp) {
                if(resp.flag) {
                  window.location.href = '/orders/new'
                }else {
                  ErrorDialog.show("前往结算发生错误")
                }
              })
            }else{
              window.location.href = '/orders/new'
            }
          }else {
            ErrorDialog.show("请至少选择一件商品")
          }
        },

        generateUrl(id) {
            return "/products/" + id
        },

        totalPrice(items) {
          return items.reduce((a, b) => a + (b.checked ? (parseFloat(b.product.msrp)*b.amount) : 0), 0)
        }
    }
}

</script>
